package yjj.system.controller;

import com.alibaba.excel.EasyExcel;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yjj.model.groups.CreateGroup;
import yjj.model.web.PageBean;
import yjj.model.web.Result;
import yjj.system.entity.User;
import yjj.system.model.SysUserDTO;
import yjj.system.service.UserService;
import yjj.utils.excel.DataListener;
import yjj.utils.excel.ExcelUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
@Tag(name = "用户管理")
public class UserController  {
    @Autowired
    UserService userService;


    @PostMapping("/findById")
    @Operation(summary = "根据id查询用户")
    public Result findById(@RequestParam String userId) {
        return Result.success(userService.findById(userId));
    }

    @PreAuthorize("hasRole('admin')")
    @GetMapping("/all")
    @Operation(summary = "获取所有用户")
    public Result listAll(){
         return Result.success(userService.listAll());
    }
    @PostMapping("/page")
    @Parameters({
            @Parameter(name = "pageNum", description = "页码", required = true),
            @Parameter(name = "pageSize", description = "每页显示数量", required = true)
    })
    @Operation(summary = "分页查询")
    public Result page(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize){
        PageBean<User> pagelist = userService.pagelist(pageNum, pageSize);
        //如果当前页码值大于总页数，返回最后一页数据
        if (pageNum > pagelist.getTotalPage()) {
            pagelist = userService.pagelist((int)pagelist.getTotalPage(), pageSize);
        }
        return Result.success(pagelist);
    }

    @PostMapping("/update")
    @Operation(summary = "更新用户信息")
    public Result update(@RequestBody SysUserDTO sysUserDTO){
        userService.update(sysUserDTO);
        return Result.success();

    }
    @PostMapping("/add")
    @Operation(summary = "添加用户")
    public Result add(@Validated(CreateGroup.class) @RequestBody  User user){

        return Result.success(userService.save(user));
    }

    @PostMapping("/search")
    @Operation(summary = "搜索用户")
    public Result search(
                         @RequestBody Map map){
        PageBean<User> pagelist =userService.search(map);
        return Result.success(pagelist);
    }

    @GetMapping("/export")
    @Operation(summary = "导出用户信息")
    public void export(HttpServletResponse response){
        String fileName = "users.xlsx";// 下载时的文件名
        String sheetName = "用户信息"; // 工作表名称
        List<User> users = userService.listAll();
        // 调用工具类进行导出
        ExcelUtil.exportExcel(response, fileName, sheetName, User.class, users);
    }
    @PostMapping("/import")
    @Operation(summary = "导入用户信息")
    public Result importUsers(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("上传的文件为空");
        }

        try (InputStream inputStream = file.getInputStream()) {
            // 创建监听器
            DataListener<User> listener = new DataListener<>(new User());

            // 读取 Excel
            EasyExcel.read(inputStream, User.class,listener).sheet().doRead();

            // 获取读取的数据
            List<User> userList = listener.getCachedDataList();

            // 这里可以添加数据验证逻辑
            userService.process(userList);


            return Result.success("导入成功，导入条数: " + userList.size());
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("导入失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入过程中出现错误: " + e.getMessage());
        }
    }
}
